package blogsys.demo.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * redis工具类
 */

@Component
public class RedisUtiles {

    @Autowired
    private  RedisTemplate<String ,Object> redisTemplate;

    private static RedisTemplate myRedisTemplate;

    private  static String key; //键

    private  final static long timeout = 60 * 60 * 60 * 24; //过期时间 一天

    private final static TimeUnit timeUnit = TimeUnit.SECONDS; //秒

    @PostConstruct //此注解表示构造时赋值
    public void redisTemplate() {
        myRedisTemplate = redisTemplate;
    }
    /**
     * 存入redis
     * @param key
     * @param value
     */
    public static void setCacheRedis(String key,Object value){
        myRedisTemplate.opsForValue().set(key,value,timeout,timeUnit);
    }

    /**
     * 自定义传入过期时间与类型
     *存入redis
     * @param key
     * @param value
     * @param timeout 过期时间
     * @param timeUnit 时间类型
     */
    public static  void setCacheRedis(String key, Object value, long timeout, TimeUnit timeUnit){
        myRedisTemplate.opsForValue().set(key,value,timeout,timeUnit);
    }

    /**
     *
     * 通过key从redis获取values
     * @param key
     * @return
     */
    public static Object getCacheRedis(String key){
        Object o = myRedisTemplate.opsForValue().get(key);
        return o;
    }

    /**
     * 获取redis所有的values
     * @return
     */
    public static Map<String,Object> getAllCacheRedis(){
        Map<String,Object> map = new HashMap<>();
        Set keys = myRedisTemplate.keys("*");
        for(Object s:keys){
            Object o = myRedisTemplate.opsForValue().get(s);
            map.put(String.valueOf(s),o);
        }

        return map;
    }
}
